var express = require('express');
var router = express.Router();
var userModel = require('../model/mongo');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'hello' });
});


/* GET home page. */
router.get('/a', function (req, res, next) {

  res.render('index', { title: 'b' });
});

/* GET home page. */
router.get('/json', function (req, res, next) {
  var type = req.query.type;
  var json = { two: [{ name: 'a', id: 1 }, { name: 'b', id: 2 }], one: { name: 'c', id: 3 } }
  if (typeof (type) != 'undefined') {
    json = { two: [{ name: 'a', id: 1 }, { name: 'b', id: 2 }], one: { name: type, id: 3 } }
    console.log('req', req.query.type);
  }

  res.json(json);
});

/* GET home page. */
router.get('/json2', function (req, res, next) {
  let newTest = [{ name: 'test', id: 1 }];
  // testModel.create(newTest, (err) => {
  //   if (err) {
  //     res.json({ rs: false });
  //   } else {
  //     res.json({ rs: true });
  //   }
  // });
});


router.post("/add", function (req, res, next) {
  console.log('req body', req.body);
  var user = new userModel({
    email: req.body.data.email,
    passwd: req.body.data.passwd,
    url: req.body.data.url
  });
  user.save(function (err) {
    if (err) {
      res.json({ rs: false });
    } else {
      res.json({ rs: true });
    }
  });
});

router.post("/findAll", function (req, res, next) {
  let query = userModel.find({});

  console.log('-------------------------', __dirname);
  query.sort({ email: 'asc' });
  query.skip(req.body.skip);
  query.limit(req.body.pageSize);
  query.exec((err, users) => {
    if (!err) {
      console.log(users);
      userModel.find(function (err, rs) {
        res.json({ resultList: users, totalCount: rs.length });
      });
    } else {
      res.json({ rs: false });
    }
  });

});

router.get('/delRecord', function (req, res, next) {
  var _id = req.query.id;
  console.log('params', _id);
  userModel.remove({ _id: _id }, (err, result) => {
    if (err) {
      res.json({ rs: false });
    } else {
      res.json({ rs: true });
    }
  })
});

module.exports = router;
